#ifndef __SPRITELIST_H__
#define __SPRITELIST_H__

#include <iostream>
#include <vector>
using namespace std;

#include <dalelib/graphics.h>
#include <dalelib/maths.h>
#include <dalelib/flipbook.h>
using namespace dalelib;

#define USE_GL_INTERLEAVED_ARRAYS_FUNCTION

class SpriteList
{
private:

	struct Vertex { v2 uv; unsigned int col; v3 pos; };
	vector<Vertex> _vertex_array;

	int _num_sprites;

public:

	const int getCapacity() { return _vertex_array.size()/4; }

	void changeCapacity(const int _Capacity) { _vertex_array.resize(_Capacity*4); clear(); }

	void clear() { _num_sprites = 0; }

	void addSprite(
		const v3 _Pos=v3(0,0,0),
		const v2 _Scl=v2(1,1),
		const float _Ang=0.f,
		const v4 _Col=v4(1,1,1,1),
		const v2 _Pivot=v2(0,0),
		const v2 _TMin=v2(0,0),
		const v2 _TMax=v2(1,1))
	{
		if(_num_sprites < getCapacity())
		{
            v2 scl = _Scl*0.5f;
			m4 m = m4::translation(_Pos)*m4::rotation(v3(0,0,_Ang));//*m4::translation(v3(_Pivot[0],_Pivot[1],0));
			unsigned int col = (int(_Col[0]*255)<<24)|(int(_Col[1]*255)<<16)|(int(_Col[2]*255)<<8)|int(_Col[3]*255);

			{
				int index = _num_sprites*4;

				_vertex_array[index].uv = v2(_TMin.x(), _TMin.y());
				_vertex_array[index].col = col;
				_vertex_array[index].pos = m.transformPoint(v3(-scl[0],-scl[1], 0.f));
				++index;

				_vertex_array[index].uv = v2(_TMax.x(), _TMin.y());
				_vertex_array[index].col = col;
				_vertex_array[index].pos = m.transformPoint(v3( scl[0],-scl[1], 0.f));
				++index;

				_vertex_array[index].uv = v2(_TMax.x(), _TMax.y());
				_vertex_array[index].col = col;
				_vertex_array[index].pos = m.transformPoint(v3( scl[0], scl[1], 0.f));
				++index;

				_vertex_array[index].uv = v2(_TMin.x(), _TMax.y());
				_vertex_array[index].col = col;
				_vertex_array[index].pos = m.transformPoint(v3(-scl[0], scl[1], 0.f));
				++index;
			}

			++_num_sprites;
		}
		else
		{
			cout << "warning, sprites being lost due to capacity limitations" << endl;
		}
	}

	void draw()
	{
#ifdef USE_GL_INTERLEAVED_ARRAYS_FUNCTION

		glInterleavedArrays( GL_T2F_C4UB_V3F, 0, &_vertex_array[0] );
		glDrawArrays( GL_QUADS, 0, _num_sprites*4 );

#else

		glVertexPointer( 3, GL_FLOAT, sizeof(Vertex), &_vertex_array[0].pos );
		glEnableClientState( GL_VERTEX_ARRAY );

		glTexCoordPointer( 2, GL_FLOAT, sizeof(Vertex), &_vertex_array[0].uv );
		glEnableClientState( GL_TEXTURE_COORD_ARRAY );

		glColorPointer( 4, GL_FLOAT, sizeof(Vertex), &_vertex_array[0].col );
		glEnableClientState( GL_COLOR_ARRAY );

		glDrawArrays( GL_QUADS, 0, _num_sprites*4 );

		glDisableClientState( GL_VERTEX_ARRAY );
		glDisableClientState( GL_TEXTURE_COORD_ARRAY );
		glDisableClientState( GL_COLOR_ARRAY );

#endif
	}

};


#endif
